package fr.insta.reverse.uml.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class InstaUtils
{

	private static final boolean INSTA_PROXY = true;

	public static String getContentFile(InputStream inputStream)
	{
		String line = "";

		StringBuilder strBuilder = new StringBuilder();

		BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

		try
		{
			while ((line = br.readLine()) != null)
			{
				strBuilder.append(line);
				strBuilder.append('\r');
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (br != null)
			{
				try
				{
					br.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}

		System.out.println(strBuilder.toString());

		return strBuilder.toString();
	}

	public static String sha1(String input) throws NoSuchAlgorithmException
	{
		if (input == null)
			return null;

		MessageDigest mDigest = MessageDigest.getInstance("SHA1");
		byte[] result = mDigest.digest(input.getBytes());
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < result.length; i++)
		{
			sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
		}
		return sb.toString();
	}

	public static boolean isEmail(String _mail)
	{
		if (_mail == null)
			return false;

		Pattern regEx = Pattern.compile("[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
		Matcher matcher = regEx.matcher(_mail);
		return matcher.find();
	}

	public static Proxy getProxyIfNeeded()
	{
		if (!INSTA_PROXY)
			return null;

		Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("172.16.13.3", 8080));

		Authenticator authenticator = new Authenticator()
		{
			@Override
			public PasswordAuthentication getPasswordAuthentication()
			{
				return (new PasswordAuthentication("s.martin", "Xzywuw94".toCharArray()));
			}
		};

		Authenticator.setDefault(authenticator);

		return proxy;
	}

}
